/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 *
 * http://www.gnu.org/copyleft/gpl.html
 */
package l1j.server.server.datatables.sql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.WorldClan;
import l1j.server.DatabaseFactory;
import l1j.server.server.IdFactory;
import l1j.server.server.datatables.CastleTable;
import l1j.server.server.datatables.storage.ClanStorage;
import l1j.server.server.model.L1Clan;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.utils.PerformanceTimer;
import l1j.server.server.utils.SQLUtil;

// Referenced classes of package l1j.server.server:
// IdFactory

public class ClanTable implements ClanStorage{

	private static Logger _log = Logger.getLogger(ClanTable.class.getName());

	private final Map<Integer, L1Clan> _clans = new HashMap<Integer, L1Clan>();

	private static ClanTable _instance;

	public static ClanTable getInstance() {
		if (_instance == null) {
			_instance = new ClanTable();
		}
		return _instance;
	}

	/**
	 * 加入虛擬血盟
	 * @param integer
	 * @param l1Clan
	 */
	@Override
	public void addDeClan(Integer integer, L1Clan l1Clan) {
		WorldClan.get().storeClan(l1Clan);
		this._clans.put(integer, l1Clan);
	}

	/**
	 * 建立血盟資料
	 * @param player
	 * @param clan_name
	 * @return
	 */
	@Override
	public L1Clan createClan(final L1PcInstance player, final String clan_name) {
		for (final L1Clan oldClans : WorldClan.get().getAllClans()) {
			if (oldClans.getClanName().equalsIgnoreCase(clan_name)) {
				return null;
			}
		}
		final L1Clan clan = new L1Clan();
		clan.setClanId(IdFactory.getInstance().nextId());
		clan.setClanName(clan_name);
		clan.setLeaderId(player.getId());
		clan.setLeaderName(player.getName());
		clan.setCastleId(0);
		clan.setHouseId(0);

		Connection con = null;
		PreparedStatement pstm = null;

		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con.prepareStatement("INSERT INTO clan_data SET clan_id=?, clan_name=?, leader_id=?, leader_name=?, hascastle=?, hashouse=?");
			pstm.setInt(1, clan.getClanId());
			pstm.setString(2, clan.getClanName());
			pstm.setInt(3, clan.getLeaderId());
			pstm.setString(4, clan.getLeaderName());
			pstm.setInt(5, clan.getCastleId());
			pstm.setInt(6, clan.getHouseId());
			pstm.execute();
		} catch (final SQLException e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}

		WorldClan.get().storeClan(clan);
		this._clans.put(clan.getClanId(), clan);

		player.setClanid(clan.getClanId());
		player.setClanname(clan.getClanName());
		player.setClanRank(L1Clan.CLAN_RANK_PRINCE);
		clan.addMemberName(player.getName());
		try {
			// DBにキャラクター情報を書き込む
			player.save();
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		}
		return clan;
	}


	/**
	 * 刪除血盟資料
	 * @param clan_name
	 */
	@Override
	public void deleteClan(final String clan_name) {
		final L1Clan clan = WorldClan.get().getClan(clan_name);
		if (clan == null) {
			return;
		}
		Connection con = null;
		PreparedStatement pstm = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con
					.prepareStatement("DELETE FROM clan_data WHERE clan_name=?");
			pstm.setString(1, clan_name);
			pstm.execute();
		} catch (final SQLException e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
		clan.getDwarfForClanInventory().clearItems();
		clan.getDwarfForClanInventory().deleteAllItems();

		WorldClan.get().removeClan(clan);
		this._clans.remove(clan.getClanId());
	}

	/**
	 * 全部血盟資料
	 * @return
	 */
	@Override
	public Map<Integer, L1Clan> get_clans() {
		return this._clans;
	}

	/**
	 * 指定血盟資料
	 * @param clan_id
	 * @return
	 */
	@Override
	public L1Clan getTemplate(final int clan_id) {
		return this._clans.get(clan_id);
	}

	/**
	 * 預先加載血盟資料
	 */
	@Override
	public void load() {
		{
			final PerformanceTimer timer = new PerformanceTimer();
			Connection cn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;

			try {
				cn = DatabaseFactory.get().getConnection();
				ps = cn.prepareStatement(
						"SELECT * FROM `clan_data` ORDER BY `clan_id`");

				rs = ps.executeQuery();
				while (rs.next()) {
					final L1Clan clan = new L1Clan();
					final int clan_id = rs.getInt("clan_id");
					clan.setClanId(clan_id);
					clan.setClanName(rs.getString("clan_name"));
					clan.setLeaderId(rs.getInt("leader_id"));
					clan.setLeaderName(rs.getString("leader_name"));
					final int castleid = rs.getInt("hascastle");
					clan.setCastleId(castleid);
					if(castleid !=0){
						CastleTable.getInstance().getCastleTable(castleid).setSrcClanid(clan_id);
					}
					clan.setHouseId(rs.getInt("hashouse"));

					WorldClan.get().storeClan(clan);
					this._clans.put(clan_id, clan);
				}

			} catch (final SQLException e) {
				_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);

			} finally {
				SQLUtil.close(rs);
				SQLUtil.close(ps);
				SQLUtil.close(cn);
			}
			_log.info("載入血盟資料資料數量: " + this._clans.size() + "(" + timer.get() + "ms)");
		}

		// 加入血盟人員名稱清單
		final Collection<L1Clan> AllClan = WorldClan.get().getAllClans();
		for (final L1Clan clan : AllClan) {
			Connection cn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;

			try {
				cn = DatabaseFactory.get().getConnection();
				ps = cn.prepareStatement(
						"SELECT `char_name` FROM `characters` WHERE `ClanID`=?");
				ps.setInt(1, clan.getClanId());
				rs = ps.executeQuery();

				while (rs.next()) {
					clan.addMemberName(rs.getString("char_name"));
				}

			} catch (final SQLException e) {
				_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);

			} finally {
				SQLUtil.close(rs);
				SQLUtil.close(ps);
				SQLUtil.close(cn);
			}
		}
		// 加載血盟倉庫資料
		for (final L1Clan clan : AllClan) {
			clan.getDwarfForClanInventory().loadItems();
		}
	}

	/**
	 * 更新血盟資料
	 * @param clan
	 */
	@Override
	public void updateClan(final L1Clan clan) {
		Connection cn = null;
		PreparedStatement ps = null;
		try {
			cn = DatabaseFactory.get().getConnection();
			ps = cn.prepareStatement(
					"UPDATE clan_data SET `clan_id`=?,`leader_id`=?," +
					"`leader_name`=?,`hascastle`=?,`hashouse`=? WHERE `clan_name`=?");
			int i = 0;
			ps.setInt(++i, clan.getClanId());
			ps.setInt(++i, clan.getLeaderId());
			ps.setString(++i, clan.getLeaderName());
			ps.setInt(++i, clan.getCastleId());
			ps.setInt(++i, clan.getHouseId());
			ps.setString(++i, clan.getClanName());
			ps.execute();

		} catch (final SQLException e) {
			_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);

		} finally {
			SQLUtil.close(ps);
			SQLUtil.close(cn);
		}
	}

}
